package top.liuzhenyu.study.javawebjdbc.dao;

import top.liuzhenyu.study.javawebjdbc.entity.TbComputer;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class TbComputerDAO {
    public static int insert(TbComputer computer) throws Exception {
        Connection conn = DBHelper.getConnection();
        String sql = "insert into tb_computer(changshang,dnjj,price) values(?,?,?)";
        PreparedStatement ps = conn.prepareStatement(sql);
        ps.setString(1,computer.getChangshang());
        ps.setString(2,computer.getDnjj());
        ps.setInt(3,computer.getPrice());
        int result = ps.executeUpdate();
        conn.close();
        return result;
    }

    public static List<TbComputer> query() throws Exception {
        List<TbComputer> list = new ArrayList<>();
        Connection conn = DBHelper.getConnection();
        String sql = "select * from tb_computer";
        PreparedStatement ps = conn.prepareStatement(sql);
        ResultSet rs = ps.executeQuery();
        while (rs.next()) {
            TbComputer computer = new TbComputer();
            computer.setId(rs.getInt("id"));
            computer.setChangshang(rs.getString("changshang"));
            computer.setDnjj(rs.getString("dnjj"));
            computer.setPrice(rs.getInt("price"));
            list.add(computer);
        }
        conn.close();
        return list;
    }

    public static int delete(Integer id) throws Exception {
        Connection conn = DBHelper.getConnection();
        String sql = "delete from tb_computer where id=?";
        PreparedStatement ps = conn.prepareStatement(sql);
        ps.setInt(1,id);
        int i = ps.executeUpdate();
        conn.close();
        return i;
    }
}
